<template>
  <div class="search-page">
    <!-- 顶部信息栏：右侧显示结果条数 -->
    <div class="flex items-center justify-between mb-6">
              <div class="text-slate-700">
        关键词：<span class="font-medium">{{ keyword || '（无）' }}</span>
      </div>
              <div class="text-slate-500">
        <span v-if="total > 0">共找到 {{ total }} 条结果</span>
        <span v-else>暂无结果</span>
      </div>
    </div>

    <!-- 搜索框（置顶） -->
    <div class="flex items-center justify-center mb-10">
      <div class="flex items-center w-full max-w-4xl">
        <el-input
          v-model="newKeyword"
          :placeholder="keyword ? '在结果中重新搜索...' : '请输入关键词进行搜索'"
          size="large"
          class="search-input-lg flex-1"
          clearable
          @keyup.enter="handleNewSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="large" class="ml-3 search-btn-lg" @click="handleNewSearch">
          搜索
        </el-button>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="loading" class="flex justify-center items-center py-20">
      <el-icon class="is-loading text-3xl text-slate-400"><Loading /></el-icon>
    </div>

    <div v-else-if="newsList.length === 0" class="text-center py-20">
      <el-empty description="没有找到相关新闻">
        <template #image>
          <el-icon class="text-6xl text-slate-300"><Search /></el-icon>
        </template>
        <el-button type="primary" @click="$router.push('/')">
          返回首页
        </el-button>
      </el-empty>
    </div>

    <div v-else class="search-results">
      <!-- 新闻列表（类似搜索引擎风格） -->
      <div>
        <div
          v-for="news in newsList"
          :key="news.id"
          class="py-4 border-b border-slate-200 hover:bg-slate-50/50 transition-colors cursor-pointer"
          @click="viewNewsDetail(news)"
        >
                        <h3 class="text-xl font-medium text-blue-600 hover:underline truncate">
            <span v-html="highlight(news.title)"></span>
          </h3>
                        <p class="mt-1 text-slate-600 line-clamp-3">
            <span v-html="highlight(news.summary || '（暂无摘要）')"></span>
          </p>
                        <div class="mt-1 text-sm text-slate-500 flex items-center space-x-4">
            <span v-if="news.sourceName">{{ news.sourceName }}</span>
            <span v-if="news.publishTime">{{ formatDate(news.publishTime) }}</span>
            <span v-if="news.categoryName">{{ news.categoryName }}</span>
          </div>
        </div>
      </div>

      <!-- 分页：有结果即显示 -->
      <div v-if="total > 0" class="flex justify-center mt-8">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({ layout: 'search' })
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Search, Folder, Link, Clock, Document, Loading } from '@element-plus/icons-vue'
import { newsAPI } from '~/services/api'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const newsList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const newKeyword = ref('')

// 计算属性
const keyword = computed(() => route.query.keyword || '')

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.style.display = 'none'
}

// 关键字高亮（简单包含匹配，区分大小写与否按需求调整）
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const highlight = (text) => {
  const kw = (keyword.value || '').trim()
  if (!kw || !text) return text
  try {
    const pattern = new RegExp(escapeRegExp(kw), 'gi')
    return String(text).replace(pattern, (m) => `<span class=\"highlight\">${m}</span>`)
  } catch (e) {
    return text
  }
}

// 加载搜索结果
const loadSearchResults = async () => {
  loading.value = true
  try {
    const data = await newsAPI.searchNews({
      keyword: keyword.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    newsList.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理新搜索
const handleNewSearch = () => {
  currentPage.value = 1
  const kw = newKeyword.value.trim()
  if (kw) {
    router.push({ path: '/search', query: { keyword: kw } })
  } else {
    router.push({ path: '/search' })
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadSearchResults()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  loadSearchResults()
}

// 查看新闻详情（新开标签页）
const viewNewsDetail = (news) => {
  if (!news || !news.id) return
  window.open(`/news/${news.id}`, '_blank')
}

// 监听路由变化
watch(
  () => route.query.keyword,
  (nextKeyword) => {
    // 同步顶部搜索框内容（允许为空）
    newKeyword.value = String(nextKeyword || '')
    currentPage.value = 1
    loadSearchResults()
  },
  { immediate: true }
)

// 页面加载时执行搜索
onMounted(() => {
  // 初次进入：同步并加载（允许空搜索）
  newKeyword.value = String(keyword.value || '')
  loadSearchResults()
})
</script>

<style scoped>
.search-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-card:hover {
  transform: translateY(-2px);
}

:deep(.highlight) {
  color: #dc2626; /* 红色 */
  background: transparent;
  font-weight: 600;
}

/* 恢复之前放大的尺寸 */
:deep(.search-input-lg .el-input__wrapper) {
  /* 与 Element Plus large 按钮等高 */
  height: var(--el-component-size-large);
  min-height: var(--el-component-size-large);
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 14px;
  padding-right: 14px;
  font-size: 16px;
}

:deep(.search-input-lg .el-input__inner) {
  font-size: 16px;
}

:deep(.search-input-lg .el-input__prefix) {
  font-size: 18px;
  display: flex;
  align-items: center;
}

:deep(.search-btn-lg) {
  padding: 14px 22px;
  font-size: 16px;
}

/* 深色模式适配 */
:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: var(--el-text-color-primary);
  --el-pagination-border-color: var(--el-border-color);
}

:deep(.el-pagination .el-pager li) {
  background-color: var(--el-bg-color);
  color: var(--el-text-color-primary);
  border: 1px solid var(--el-border-color);
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: var(--el-color-primary);
  color: white;
  border-color: var(--el-color-primary);
}
</style>

